#include "jpg.h"

struct LCD_info
{
    int fd;
    int width;
    int height;
    int bpp;
    int screen_size;

    char *fb_mem;
};

void init_LCD(struct LCD_info *lcdinfo)
{
    lcdinfo->fd = open("/dev/fb0", O_RDWR);
    struct fb_var_screeninfo vinfo;
    ioctl(lcdinfo->fd, FBIOGET_VSCREENINFO, &vinfo);
    lcdinfo->width = vinfo.xres;
    lcdinfo->height= vinfo.yres;
    lcdinfo->bpp   = vinfo.bits_per_pixel;
    lcdinfo->screen_size = lcdinfo->width * lcdinfo->height * lcdinfo->bpp/8 ;

    // 帧缓冲设备(LCD)申请映射内存
    lcdinfo->fb_mem = mmap(NULL, lcdinfo->screen_size, PROT_WRITE, MAP_SHARED, lcdinfo->fd, 0);
}

int main(int argc, char const *argv[]) // ./a.out xx.jpg
{
    if(argc != 2)
    {
        printf("请指定一张JPEG图片\n");
        exit(0);
    }

    // 1. 初始化LCD
    struct LCD_info lcd_info;
    init_LCD(&lcd_info);

    // 2. 加载并解码JPG
    struct jpeg_info *jinfo = jpg2rgb(argv[1]);

    // 3. 显示JPEG
    for(int j=0; j<lcd_info.height && j<jinfo->height; j++)
    {
        for(int i=0; i<lcd_info.width && i<jinfo->width; i++)
        {
            memcpy(lcd_info.fb_mem+4*i + 800*4*j,     jinfo->rgb_data+3*i + jinfo->width*3*j + 2, 1);
            memcpy(lcd_info.fb_mem+4*i + 800*4*j + 1, jinfo->rgb_data+3*i + jinfo->width*3*j + 1, 1);
            memcpy(lcd_info.fb_mem+4*i + 800*4*j + 2, jinfo->rgb_data+3*i + jinfo->width*3*j,     1);
        }
    }
    return 0;
}
